package com.example.flutter_track

import android.os.SystemClock
import android.util.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import java.io.File
import java.io.FileOutputStream
import java.io.PrintWriter
import java.time.Instant
import java.util.Date

class MainActivity : FlutterActivity() {
    companion object {
        const val TAG = "flutter_main_activity"
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        Log.d(TAG, "register flutter plugin..., $flutterEngine")

        Thread.setDefaultUncaughtExceptionHandler { t, e ->
            Log.e(TAG, "thread: ${t.id}, name: ${t.name}, Uncaught exception: ", e)
//            saveCrashLogToFile(e)
        }
    }

//    private fun saveCrashLogToFile(throwable: Throwable) {
//        try {
//            // 获取应用的文件目录
//            val dir = getExternalFilesDir(null)
//            if (dir != null) {
//                val crashLogFile = File(dir, "crash_log_${SystemClock.elapsedRealtimeNanos()}.txt")
//                FileOutputStream(crashLogFile, true).use { fos ->
//                    PrintWriter(fos).use { writer ->
//                        writer.println("Crash occurred: ${throwable.message}")
//                        throwable.stackTrace.forEach { element ->
//                            writer.println(element.toString())
//                        }
//                    }
//                }
//                Log.i(TAG, "Crash log saved to: ${crashLogFile.absolutePath}")
//            }
//        } catch (e: Exception) {
//            Log.e(TAG, "Failed to save crash log", e)
//        }
//    }
}
